<?php
namespace app\common\controller\storage;

use Exception;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 阿里云对象存储 OSS
 */
class AliYunOss extends Upload
{
    /**
     * 上传文件到阿里云OSS
     */
    public function upload($name)
    {
        // 配置参数
		// $data = [
		// 	// Access Key ID
		//     'accessKey' => 'LTAI4G9Ta4i2UgVPjFKEFgnU',  
		//     // Access Key Secret
		//     'secretKey' => 'QwqugGy9gEUoszjyuQy4G5ycgGaYO3',
		//     // 阿里云oss 外网地址endpoint
		//     'endpoint'  => 'oss-cn-beijing.aliyuncs.com',
		//     // Bucket名称
		//     'bucket'    => 'chenduxiu',
		//     // 访问域名
		//     'domain'    => 'https://cdn.itqaq.com',
		// ];
        // $bucket          = $data['bucket'];
        // $domain          = $data['domain'];
        // $endpoint        = $data['endpoint'];
        // $accessKey       = $data['accessKey'];
        // $secretKey = $data['secretKey'];
        
        $bucket    = $this->storageConfig['bucket'];
        $domain    = $this->storageConfig['domain'];
        $endpoint  = $this->storageConfig['endpoint'];
        $accessKey = $this->storageConfig['accessKey'];
        $secretKey = $this->storageConfig['secretKey'];

        // 获取 \think\File 对象
		$file = $this->isUpload($name);
        // 判断是否有文件上传
        if ( ! $file instanceof \think\File ) return $file;

		// 将文件上传到阿里云
		try {
            // 实例化对象 将配置传入
            $ossClient = new OssClient($accessKey, $secretKey, $endpoint);

            // 文件在存储空间中的存放位置
            $path = $this->buildSaveName($file);

            //执行阿里云上传 bucket名称,上传的目录,文件
            $result = $ossClient->uploadFile($bucket, $path, $file->getRealPath());

            // 配置了自有域名使用则自有域名
            // 否则使用阿里云OSS提供的默认域名
            if ( empty($domain) ) {
            	$url = $result['info']['url'];
            } else {
            	$url = $domain . '/' . $path;
            }
        } catch (OssException $e) {
            return $this->fail($e->getMessage());
        }
        // 文件上传成功
        return $this->achieve($url);
    }
}
